﻿using CRM.Models;
using System.Linq;
using System.Threading.Tasks;
using System;
using System.Collections.Generic;
using Z.EntityFramework.Plus;

namespace CRM.Services
{
    public class ValidityService : BaseService
    {
        private readonly MyDbContext _dbContext;

        public ValidityService(MyDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        /// <summary>
        /// 获取当前公司实际有效期
        /// </summary>
        /// <param name="idString"></param>
        /// <returns></returns>
        public Validity GetMaxValidity(string idString) {
            var ids = idString.Split(',').Select(x => Convert.ToInt32(x));
            return _dbContext.Validity.Where(m => ids.Contains(m.Id)).OrderByDescending(m => m.validity).FirstOrDefault();
        }

        /// <summary>
        /// 增加公司有效期数据
        /// </summary>
        /// <param name="validity"></param>
        /// <returns></returns>
        public async Task<int>  InitValidity(long validity) {
            Validity validityModel = new() { 
                validity = validity
            };
            await _dbContext.Validity.AddAsync(validityModel);
            await _dbContext.SaveChangesAsync();

            return validityModel.Id;
        }

        /// <summary>
        /// 更新指定有效期时间戳
        /// </summary>
        /// <param name="id"></param>
        /// <param name="validity"></param>
        /// <returns></returns>
        public int UpdateValidity(int id, long validity)
        {
            var dic = new Dictionary<string, object>
            {
                ["validity"] = validity
            };
            return _dbContext.Validity.Where(m => m.Id == id).Update(dic);
        }
    }
}
